package com.xiaouyudeguang.common.exception;

import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
import com.xiaouyudeguang.common.GlobalExceptionHandler;
import com.xiaouyudeguang.common.respose.ResultDto;
import com.xiaouyudeguang.common.utils.I18nUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.SQLException;

@Slf4j
@ResponseBody
@ControllerAdvice
public class GlobalExceptionController {

    @Autowired(required = false)
    private GlobalExceptionHandler globalExceptionHandler;

    /**
     * s
     * 用于处理异常的
     *
     * @return
     */
    @ExceptionHandler(Exception.class)
    public ResultDto<Object> exception(Exception e) {
        String message = e.getMessage();
        if (globalExceptionHandler != null) {
            message = globalExceptionHandler.handleException(e);
        }
        log.error(message, e);
        int code = 1;
        if (e instanceof NullPointerException) {
//            return ResultDto.err(10001, "空指针异常");
            code = 10001;
        }
        if (e instanceof ArrayIndexOutOfBoundsException) {
//            return ResultDto.err(10002, "数组越界异常");
            code = 10002;
        }
        if (e instanceof ClassCastException) {
//            return ResultDto.err(10003, "强制类型转换异常");
            code = 10003;
        }
        if (e instanceof NumberFormatException) {
//            return ResultDto.err(10004, "数字格式化异常");
            code = 10004;
        }
        if (e instanceof IndexOutOfBoundsException) {
//            return ResultDto.err(10005, "索引越界异常");
            code = 10005;
        }
        if (e instanceof FileNotFoundException) {
//            return ResultDto.err(10007, "文件丢失异常");
            code = 10006;
        }
        if (e instanceof IOException) {
//            return ResultDto.err(10008, "IO异常");
            code = 10007;
        }
        if (e instanceof SQLException) {
//            return ResultDto.err(10006, "SQL执行异常");
            code = 10008;
        }
        if (e instanceof MybatisPlusException) {
//            return ResultDto.err(10006, "数据异常");
            code = 10009;
        }
        return ResultDto.result(code, e.getMessage(), "发生错误，请联系客服处理");
    }

    /**
     * 用于处理异常的
     *
     * @return
     */
    @ExceptionHandler(BusinessException.class)
    public ResultDto<Object> exception(BusinessException e) {
        String message = e.getMessage();
        if (globalExceptionHandler != null) {
            message = globalExceptionHandler.handleException(e);
        }
        log.error(message, e);
        return ResultDto.failure(e.getCode(), I18nUtils.getMessage(String.valueOf(e.getCode()), null, message));
    }

}